﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace EmployeeCheckIn
{
    public partial class UpdateAdmin : System.Web.UI.Page
    {
        int i;
        string NowUserDB;
        StringBuilder sb = new StringBuilder();
        protected void Page_Load(object sender, EventArgs e)
        {
            
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragma", "no-cache");
            Response.Expires = -1;
            Session["updateadmin"] = null;
            if (Session["User"] != null && Session["Pass"] != null)
            {
                if (!IsPostBack)
                {
                    Session["updateadmin"] = null;
                    i = Convert.ToInt32(Session["AdminEdit_id"].ToString());

                    dataGridDetail(i);
                    int j = Convert.ToInt32(Session["admin_id"]);
                    Selectdata sl = new Selectdata();
                    DataTable dt = sl.SelectAdminData(j);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        NowUserDB = dt.Rows[0]["user_name"].ToString();

                    }
                }
                if (IsPostBack)
                {
                    Session["updateadmin"] = null;
                    i = Convert.ToInt32(Session["AdminEdit_id"].ToString());
                    int j = Convert.ToInt32(Session["admin_id"]);
                    Selectdata sl = new Selectdata();
                    DataTable dt = sl.SelectAdminData(j);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        NowUserDB = dt.Rows[0]["user_name"].ToString();

                    }
                }
            }
            else
            {
                Response.Redirect("Default.aspx");

            }

        }
        private void dataGridDetail(int i)
        {
            DataTable dt = GetData(i);

            if (dt != null && dt.Rows.Count > 0)
            {

                txtUserName.Text = dt.Rows[0]["user_name"].ToString().ToLower();
                hdfUsername.Value = dt.Rows[0]["user_name"].ToString().ToLower();
                rblTitleAdmin.SelectedValue = dt.Rows[0]["admin_title"].ToString();
                txtName.Text = dt.Rows[0]["admin_name"].ToString();
                txtLastname.Text = dt.Rows[0]["admin_lastname"].ToString();
                txtPhone.Text = dt.Rows[0]["admin_phone"].ToString();
                txtDateRegis.Text = Convert.ToDateTime(dt.Rows[0]["admin_date_regis"].ToString()).ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("th-TH"));
                ddlAdminStatus.SelectedValue = dt.Rows[0]["admin_status_id"].ToString();
                

            }
        }
        private DataTable GetData(int i)
        {
            string sqltext = @"select user_name
                                     ,admin_title
                                     
                                     ,admin_name
                                     ,admin_lastname 
                                     ,admin_phone
                                     ,admin_date_regis
                                     ,admin_status_id                                  
                                                                         
                                     from tbl_log_in 
                                      WHERE admin_id = " + i + "";
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }
        public void UpdateName(Log_inEntity enLog, int id)
        {

            string sqltext = @"UPDATE TBL_LOG_IN
                               SET USER_NAME   = @user_name
                                ,ADMIN_NAME     = @admin_name
                                ,ADMIN_LASTNAME = @admin_lastname
                                ,ADMIN_phone    = @admin_phone
                                ,ADMIN_DATE_EDIT = GETDATE()
                                ,ADMIN_STATUS_ID = @admin_status_id
                                ,ADMIN_TITLE = @admin_title
                                ,update_By = @update_by
                               WHERE ADMIN_ID = " + id + "";


            SqlCommand sqlcomm = new SqlCommand();
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            sqlcomm.Connection = sqlconn;
            sqlcomm.CommandType = System.Data.CommandType.Text;
            sqlcomm.CommandText = sqltext;
            sqlcomm.Parameters.AddWithValue("@user_name", enLog.username);
            sqlcomm.Parameters.AddWithValue("@admin_name", enLog.adminNAME);
            sqlcomm.Parameters.AddWithValue("@admin_lastname", enLog.adminLASTNAME);
            sqlcomm.Parameters.AddWithValue("@admin_phone", enLog.adminPHONE);
            sqlcomm.Parameters.AddWithValue("@update_by", enLog.updateBy);
            sqlcomm.Parameters.AddWithValue("@admin_status_id", enLog.adminSTATUS_ID);
            sqlcomm.Parameters.AddWithValue("@admin_title", enLog.adminTITLE);

            try
            {
                sqlcomm.Connection.Open();
                sqlcomm.ExecuteNonQuery();
            }
            catch (Exception)
            {

                sqlcomm.Connection.Close();
                sqlcomm.Connection.Dispose();
            }
            sqlcomm.Connection.Close();
            sqlcomm.Connection.Dispose();

        }
        private void lbEmpty()
        {
            lbWarnNAme.Visible = false;
            lbWarnPhone.Visible = false;
            lbWarnUser.Visible = false;
            lbWarnlsn.Visible = false;
            lbWarnHaveUser.Visible = false;

        }
        public DataTable GetUserNameInDb(string U)
        {

            DataTable dt = new DataTable();
            string sqltext = "select * from TBL_LOG_IN Where user_name = '" + U + "'; ";
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
        public bool checknumber(string s)
        {
            //bool result = false;
            //string Str = s.Trim();
            //double Num;
            //bool isNum = double.TryParse(Str, out Num);
            //if (isNum)
            //{ 
            //    result = true; 
            //}
            //return result;

            bool result = false;
            try
            {
                Convert.ToDouble(s);
                result = true;
            }
            catch (Exception)
            {
                result = false;

            }
            return result;
        }      
        protected void btSumit_Click(object sender, EventArgs e)
        {
            if (Session["User"] != null && Session["Pass"] != null)
            {
                lbEmpty();
                bool resault = true;
                bool phoneNull = true;
                Log_inEntity enLog = new Log_inEntity();
                string Username = txtUserName.Text;
                DataTable dt = GetUserNameInDb(Username);
                string s = "";
                if (txtUserName.Text=="")
                {
                    lbWarnUser.Visible = true;
                    resault = false;
                    s = s + "Username";
                }
                if (!(dt != null && dt.Rows.Count > 0))
                {
                    resault = true;
                   
                }
                if (dt != null && dt.Rows.Count > 0 && hdfUsername.Value != txtUserName.Text)
                {
                    s += "exit user";
                    string UserDB = dt.Rows[0]["user_name"].ToString();
                        lbWarnHaveUser.Visible = true;
                        resault = false;                     
                        //username avalible                    
                }
                 if (txtName.Text == "")
                {
                    lbWarnNAme.Visible = true;
                    resault = false;
                    s += "fname";
                }
                 if (txtLastname.Text == "")
                 {
                     lbWarnlsn.Visible = true;
                     resault = false;
                     s += "lname";
                 }
                 if (checknumber(txtPhone.Text) == false)
                {
                    if (txtPhone.Text == "")
                    {
                        phoneNull = true;
                        resault = true;
                    }
                    else
                    {
                        lbWarnPhone.Visible = true;
                        resault = false;
                        phoneNull = false;
                        s += "phone";
                    }
                     
                }
                if (resault==false||phoneNull==false)
                {
                    return;
                   
                }
                if (s==""&&phoneNull==true)
                {
                    enLog.username = txtUserName.Text.ToLower();
                    enLog.adminNAME = txtName.Text;
                    enLog.adminLASTNAME = txtLastname.Text;
                    enLog.adminPHONE = txtPhone.Text;
                    enLog.updateBy = Session["User"].ToString();
                    enLog.adminSTATUS_ID = Convert.ToInt32(ddlAdminStatus.SelectedValue);
                    enLog.adminTITLE = Convert.ToInt32(rblTitleAdmin.SelectedValue);
                    UpdateName(enLog, i);
                    Response.Write("<script>alert('แก้ไขข้อมูลเรียบร้อยแล้ว!'); window.location='ListAdmin.aspx';</script>");
                    Server.Transfer("ListAdmin.aspx");
                }

               
            }
            else
            {
                Response.Redirect("Default.aspx");

            }
        }                                 
        protected void Button1_Click(object sender, EventArgs e)
        {
            Session["updateadmin"] = null;
            if (Session["User"] != null && Session["Pass"] != null)
            {
                
                    Session["updateadmin"] = null;
                    i = Convert.ToInt32(Session["AdminEdit_id"].ToString());  
                    dataGridDetail(i);
                
                
                    Session["updateadmin"] = null;
                    i = Convert.ToInt32(Session["AdminEdit_id"].ToString());
                
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (Session["User"] != null && Session["Pass"] != null)
            {
                Server.Transfer("ListAdmin.aspx");
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }
    }
}